package cn.javablog.controller;


import cn.hutool.crypto.SecureUtil;
import cn.javablog.Vo.PageVo;
import cn.javablog.Vo.User;
import cn.javablog.Vo.UserVo;
import cn.javablog.common.lang.Result;
import cn.javablog.entity.TUser;
import cn.javablog.service.TUserService;
import cn.javablog.shiro.JwtFilter;
import cn.javablog.util.JwtUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.util.Assert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author AllenYe
 * @since 2020-08-31
 */
@Slf4j
@RestController
@RequestMapping("/admin")
public class TUserController {
    @Autowired
    private TUserService tUserService;
    @Autowired
    private JwtUtils jwtUtils;
    private final Logger logger = LoggerFactory.getLogger(TUserController.class);

    /**
     * 登录
     * @param user
     * @param response
     * @return
     */
    @PostMapping("/login")
    public Result login(@Validated @RequestBody User user, HttpServletResponse response){
        QueryWrapper<TUser> queryWrapper = new QueryWrapper<TUser>().eq("username",user.getUsername());
        TUser tUser = tUserService.getOne(queryWrapper);
        Assert.notNull(tUser,"用户名不存在");
        if(!tUser.getPassword().equals(SecureUtil.md5(user.getPassword()))){
            return Result.fail("密码错误");
        }
        if(!tUser.getType().equals(1)){
            return  Result.fail("该用户没有后台管理权限");
        }
        if (tUser.getType()!=1){
            return Result.fail("该用户没有访问后台管理系统的权限");
        }
        String jwt = jwtUtils.generateToken(tUser);
        response.setHeader("Authorization",jwt);
        response.setContentType("text/html;charset=UTF-8");
        response.setHeader("Access-Control-Expose-Headers","Authorization");
        return Result.succ(tUser);
    }

    /**
     * 退出登录
     * @return
     */
    @RequiresAuthentication
    @GetMapping("/logout")
    public Result logout(){
        SecurityUtils.getSubject().logout();
        return Result.succ(null);
    }

    /**
     * 分页查询user
     * @param pageVo
     * @return
     */
    @RequiresAuthentication
    @PostMapping("/list")
    public Result userList(@RequestBody PageVo pageVo){
        Page page = new Page(pageVo.getPageCurrent() == 0 ? 1 : pageVo.getPageCurrent(),pageVo.getPageSize() == 0 ? 10 : pageVo.getPageSize());
        QueryWrapper<TUser> tUser = new QueryWrapper<>();
        tUser.like("userName",pageVo.getName()).orderByDesc("create_time");
        tUser.ge("type",1);
        IPage tPage = tUserService.page(page, tUser);
        return Result.succ(tPage);
    }

    /**
     * 添加用户
     * @param userVo
     * @return
     */
    @RequiresAuthentication
    @PostMapping("/add")
    public Result userAdd(@Validated @RequestBody UserVo userVo){
        TUser tUser = tUserService.getOne(new QueryWrapper<TUser>().eq("username", userVo.getUserName()));
        if(null!=tUser){
            return Result.fail("用户名称不能重复");
        }
        TUser t = new TUser();
        t.setAvatar("https://unsplash.it/100/100?image=1005");
        t.setCreateTime(new Date());
        t.setUpdateTime(new Date());
        t.setEmail(userVo.getEmail());
        t.setNickname(userVo.getNickname());
        t.setUsername(userVo.getUserName());
        t.setPassword(userVo.getPassword());
        t.setType(userVo.getType());
        boolean userFlag = tUserService.save(t);
        if(userFlag){
            return Result.succ("添加用户成功",null);
        }else{
            return Result.fail("添加用户失败");
        }
    }

    /**
     * 修改用户
     * @param userVo
     * @return
     */
    @RequiresAuthentication
    @PostMapping("/edit")
    public Result userEdit(@Validated @RequestBody UserVo userVo){
        TUser tUser = tUserService.getOne(new QueryWrapper<TUser>().eq("username", userVo.getUserName()));
        TUser tUser1 = tUserService.getOne(new QueryWrapper<TUser>().eq("id", userVo.getId()));
        Assert.notNull(tUser1,"该用户不存在");
        if(!tUser.getId().equals(tUser1.getId())){
            return Result.fail("用户名不能重复");
        }
        TUser t = new TUser();
        t.setAvatar("https://unsplash.it/100/100?image=1005");
        t.setUpdateTime(new Date());
        t.setEmail(userVo.getEmail());
        t.setNickname(userVo.getNickname());
        t.setUsername(userVo.getUserName());
        t.setPassword(userVo.getPassword());
        t.setType(userVo.getType());
        boolean userFlag = tUserService.update(t,new QueryWrapper<TUser>().eq("id",userVo.getId()));
        if(userFlag){
            return Result.succ("修改用户成功",null);
        }else{
            return Result.fail("修改用户失败");
        }
    }

    /**
     * 删除用户
     * @param id
     * @return
     */
    @RequiresAuthentication
    @RequestMapping("/del")
    public Result userDel(@RequestParam int id){
        TUser tUser = tUserService.getById(id);
        Assert.notNull(tUser,"该用户不存在");
        tUser.setType(0);
        boolean b = tUserService.updateById(tUser);
        if(b){
            return Result.succ("删除用户成功",null);
        }else{
            return Result.fail("删除用户失败");
        }
    }
}
